const path=require('path');
const fs=require('fs');
const express=require('express');
const hbs=require('handlebars');
const multer=require('multer');
const app=express();

const upload=multer({
    storage:multer.diskStorage({
        destination:(req,file,cb)=>{
            let username=req.body.username;
            //console.log('destination file:',file);
            if(!username)return cb('No username');
            cb(null,'./albums/'+username);
        },
        filename:(req,file,cb)=>{
            console.log('filename file:',file);
            cb(null,Date.now()+'-'+file.originalname);
        }
    }),
    fileFilter:(req,file,cb)=>{
        //console.log('fileFilter file:',file);
        if('image/jpeg'!==file.mimetype)return cb(null,false);//返回false，拒绝接此收文件（静默失败，不会报错）
        if(file.originalname.includes('**'))return cb('文件名包含非法字符');//报错，拒绝接收所有文件并将错误传递至路由
        cb(null,true);//返回true，接收文件
    },
    limits:{
        fileSize:800*1024//单位B,超过此大小不会被上传
    }
});

app.use(express.static(path.resolve(__dirname,'albums')));

app.get('/album',(req,res)=>{
    res.sendFile(path.resolve(__dirname,'./views/album.html'));
});

const renderShow=data=>hbs.compile(fs.readFileSync(path.resolve(__dirname,'./views/show.hbs')).toString())(data);
app.post('/album',upload.array('photos'),(req,res,next)=>{
    console.log('/album req.files:',req.files);
    let files=req.files.map(file=>{
       file.src=req.body.username+'/'+file.filename;
       return file;
    });
    res.send(renderShow({files}));
});

app.use((err,req,res,next)=>{
    console.log('Upload err:\n',err);
    if('File too large'==err.message)return res.status(500).send('错误：上传文件超过800KB');
    res.status(500).send('Upload err:\n'+err);
});

//Listen
app.listen(4000,()=>{
    console.log('----------------Multer @4000-----',new Date().toLocaleTimeString());
});